package com.weiwei.diancan.utils;

import android.app.Activity;
import android.util.Log;

import java.util.Stack;

/**
 * Conpany:成都欧品在线电子商务有限公司技术服务中心
 * Auther:孙福义
 * Date: 2016/1/26
 * Effect: Activity栈管理器
 */
public class ActivityManager {
    private static ActivityManager instance;
    private Stack<Activity> activityStack;// activity栈

    private ActivityManager() {
    }

    // 单例模式
    public static ActivityManager getInstance() {
        if (instance == null) {
            instance = new ActivityManager();
        }
        return instance;
    }

    // 把一个activity压入栈中
    public void pushOneActivity(Activity actvity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(actvity);
        Log.d("MyActivityManager ", "size = " + activityStack.size());
    }

    // 获取栈顶的activity，先进后出原则
    public Activity getLastActivity() {
        if (activityStack != null) {
            return activityStack.lastElement();

        }
        return null;
    }

    // 移除一个activity
    public void popOneActivity(Activity activity) {
        if (activityStack != null && activityStack.size() > 0) {
            if (activity != null) {
                activity.finish();
                activityStack.remove(activity);
                activity = null;
            }
        }
    }

    // 退出所有activity
    public void finishAllActivity() {
        if (activityStack != null) {
            while (activityStack.size() > 0) {
                Activity activity = getLastActivity();
                if (activity == null)
                    break;
                popOneActivity(activity);
            }
        }
    }

    // 退出所有activity保留栈底的activity
    public void finishActivity() {
        if (activityStack != null) {
            while (activityStack.size() > 0) {
                Activity activity = getLastActivity();
                if (activityStack.size() == 1)
                    break;
                popOneActivity(activity);
            }
        }
    }
}
